<template>
  <view class="user-page">
    <!-- 用户头部信息 -->
    <view class="user-header">
      <view class="user-avatar">
        <image 
          src="/static/avatar-placeholder.png" 
          mode="aspectFill"
          class="avatar-image"
        ></image>
      </view>
      <view class="user-info">
        <view class="user-name">{{ userInfo ? '微信用户' : '未登录' }}</view>
        <view v-if="userInfo" class="user-id">OpenID: {{ formatOpenId(userInfo.openid) }}</view>
        <view v-else class="user-tip">点击下方按钮登录</view>
      </view>
    </view>
    
    <!-- 登录状态卡片 -->
    <view class="status-card card">
      <view class="card-title">登录状态</view>
      <view class="status-item">
        <text class="status-label">状态：</text>
        <text :class="['status-value', isLoggedIn ? 'status-success' : 'status-info']">
          {{ isLoggedIn ? '已登录' : '未登录' }}
        </text>
      </view>
      <view v-if="isLoggedIn && userInfo" class="status-item">
        <text class="status-label">OpenID：</text>
        <text class="status-value">{{ formatOpenId(userInfo.openid) }}</text>
      </view>
      <view v-if="isLoggedIn && userInfo && userInfo.unionid" class="status-item">
        <text class="status-label">UnionID：</text>
        <text class="status-value">{{ formatOpenId(userInfo.unionid) }}</text>
      </view>
      <view v-if="isLoggedIn" class="status-item">
        <text class="status-label">Token：</text>
        <text class="status-value">{{ formatToken(token) }}</text>
      </view>
    </view>
    
    <!-- 功能菜单 -->
    <view class="menu-list">
      <view class="menu-item" @click="goToRainfall">
        <view class="menu-icon">🌧️</view>
        <view class="menu-text">雨情实测</view>
        <view class="menu-arrow">›</view>
      </view>
      <view class="menu-item" @click="goToHydrology">
        <view class="menu-icon">💧</view>
        <view class="menu-text">水情监测</view>
        <view class="menu-arrow">›</view>
      </view>
      <view class="menu-item" @click="goToWeather">
        <view class="menu-icon">🌤️</view>
        <view class="menu-text">天气预报</view>
        <view class="menu-arrow">›</view>
      </view>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button 
        v-if="!isLoggedIn" 
        class="button-primary" 
        @click="handleLogin"
      >
        立即登录
      </button>
      <button 
        v-else 
        class="button-secondary" 
        @click="handleLogout"
      >
        退出登录
      </button>
    </view>
    
    <!-- 关于信息 -->
    <view class="about-section">
      <view class="about-item" @click="goToServiceAgreement">
        <text class="about-link">服务协议</text>
      </view>
      <text class="about-divider">|</text>
      <view class="about-item" @click="goToPrivacy">
        <text class="about-link">隐私条款</text>
      </view>
    </view>
    
    <view class="version-info">
      <text class="version-text">知讯水务 v0.1.0</text>
    </view>
  </view>
</template>

<script>
const authService = require('../../services/auth.js');

export default {
  data() {
    return {
      userInfo: null,
      isLoggedIn: false,
      token: ''
    }
  },
  
  onLoad() {
    this.loadUserInfo();
  },
  
  onShow() {
    // 每次显示页面时刷新用户信息
    this.loadUserInfo();
  },
  
  methods: {
    /**
     * 加载用户信息
     */
    async loadUserInfo() {
      this.isLoggedIn = authService.isLoggedIn();
      this.token = authService.getToken();
      
      if (this.isLoggedIn) {
        try {
          const userInfo = await authService.getUserInfo();
          this.userInfo = userInfo;
          console.log('用户信息:', userInfo);
        } catch (err) {
          console.error('获取用户信息失败:', err);
        }
      }
    },
    
    /**
     * 格式化 OpenID / UnionID（只显示前后各8位）
     */
    formatOpenId(id) {
      if (!id) return '-';
      if (id.length <= 16) return id;
      return `${id.substring(0, 8)}...${id.substring(id.length - 8)}`;
    },
    
    /**
     * 格式化 Token（只显示前后各8位）
     */
    formatToken(token) {
      if (!token) return '-';
      if (token.length <= 16) return token;
      return `${token.substring(0, 8)}...${token.substring(token.length - 8)}`;
    },
    
    /**
     * 触发登录
     */
    handleLogin() {
      uni.showLoading({
        title: '登录中...',
        mask: true
      });
      
      uni.login({
        provider: 'weixin',
        success: (res) => {
          if (res.code) {
            console.log('获取到 code:', res.code);
            
            // 发送 code 到后端
            uni.request({
              url: 'https://ws.waterism.tech:8090/api/wechat/login',
              method: 'POST',
              data: {
                code: res.code
              },
              success: (res) => {
                uni.hideLoading();
                
                if (res.data && res.data.success) {
                  // 保存 token
                  const token = res.data.session_token;
                  uni.setStorageSync('session_token', token);
                  
                  // 更新全局数据
                  const app = getApp();
                  app.globalData.session_token = token;
                  app.globalData.userInfo = {
                    openid: res.data.openid,
                    unionid: res.data.unionid
                  };
                  
                  console.log('登录成功');
                  console.log('OpenID:', res.data.openid);
                  console.log('Token:', token);
                  
                  uni.showToast({
                    title: '登录成功',
                    icon: 'success'
                  });
                  
                  // 刷新用户信息
                  setTimeout(() => {
                    this.loadUserInfo();
                  }, 500);
                } else {
                  uni.showToast({
                    title: res.data.message || '登录失败',
                    icon: 'none'
                  });
                  console.error('后端登录失败:', res.data);
                }
              },
              fail: (err) => {
                uni.hideLoading();
                uni.showToast({
                  title: '网络错误',
                  icon: 'none'
                });
                console.error('请求失败:', err);
              }
            });
          } else {
            uni.hideLoading();
            uni.showToast({
              title: '登录失败',
              icon: 'none'
            });
            console.error('uni.login 失败:', res.errMsg);
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({
            title: '登录失败',
            icon: 'none'
          });
          console.error('uni.login 失败:', err);
        }
      });
    },
    
    /**
     * 退出登录
     */
    handleLogout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            const token = uni.getStorageSync('session_token');
            
            if (token) {
              // 调用后端退出接口
              uni.request({
                url: 'https://ws.waterism.tech:8090/api/wechat/logout',
                method: 'POST',
                header: {
                  'Authorization': `Bearer ${token}`
                },
                complete: () => {
                  // 清除本地数据
                  uni.removeStorageSync('session_token');
                  
                  // 清除全局数据
                  const app = getApp();
                  app.globalData.session_token = null;
                  app.globalData.userInfo = null;
                  
                  // 清空页面数据
                  this.userInfo = null;
                  this.isLoggedIn = false;
                  this.token = '';
                  
                  uni.showToast({
                    title: '已退出登录',
                    icon: 'success'
                  });
                  
                  console.log('已退出登录');
                }
              });
            } else {
              // 没有 token 也清空数据
              this.userInfo = null;
              this.isLoggedIn = false;
              this.token = '';
            }
          }
        }
      });
    },
    
    /**
     * 跳转到雨情页面
     */
    goToRainfall() {
      uni.navigateTo({
        url: '/pages/services/rainfall-measured'
      });
    },
    
    /**
     * 跳转到水情页面
     */
    goToHydrology() {
      uni.navigateTo({
        url: '/pages/services/hydrology'
      });
    },
    
    /**
     * 跳转到天气页面
     */
    goToWeather() {
      uni.navigateTo({
        url: '/pages/services/weather'
      });
    },
    
    /**
     * 跳转到服务协议
     */
    goToServiceAgreement() {
      uni.navigateTo({
        url: '/pages/legal/service-agreement'
      });
    },
    
    /**
     * 跳转到隐私条款
     */
    goToPrivacy() {
      uni.navigateTo({
        url: '/pages/legal/privacy'
      });
    }
  }
}
</script>

<style scoped>
.user-page {
  min-height: 100vh;
  background: #f5f6f7;
  padding-bottom: 40rpx;
}

/* 用户头部 */
.user-header {
  background: linear-gradient(135deg, #07c160 0%, #05a650 100%);
  padding: 80rpx 32rpx 60rpx;
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: #ffffff;
  overflow: hidden;
  margin-right: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.avatar-image {
  width: 100%;
  height: 100%;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 36rpx;
  font-weight: 600;
  color: #ffffff;
  margin-bottom: 12rpx;
}

.user-id {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.user-tip {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
}

/* 状态卡片 */
.status-card {
  margin: 24rpx 32rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 24rpx;
}

.status-item {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  font-size: 28rpx;
}

.status-item:last-child {
  margin-bottom: 0;
}

.status-label {
  color: #666666;
  min-width: 140rpx;
}

.status-value {
  color: #333333;
  flex: 1;
  word-break: break-all;
}

/* 功能菜单 */
.menu-list {
  background: #ffffff;
  margin: 0 32rpx 24rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  font-size: 48rpx;
  margin-right: 24rpx;
}

.menu-text {
  flex: 1;
  font-size: 32rpx;
  color: #333333;
}

.menu-arrow {
  font-size: 48rpx;
  color: #cccccc;
}

/* 操作按钮 */
.action-buttons {
  padding: 0 32rpx;
  margin-bottom: 40rpx;
}

.button-primary,
.button-secondary {
  width: 100%;
  padding: 28rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 500;
  border: none;
}

.button-primary {
  background: #07c160;
  color: #ffffff;
}

.button-secondary {
  background: #ffffff;
  color: #ff3b30;
  border: 2rpx solid #ff3b30;
}

/* 关于信息 */
.about-section {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16rpx;
}

.about-item {
  padding: 8rpx 16rpx;
}

.about-link {
  font-size: 26rpx;
  color: #666666;
}

.about-divider {
  font-size: 26rpx;
  color: #cccccc;
}

.version-info {
  text-align: center;
}

.version-text {
  font-size: 24rpx;
  color: #999999;
}
</style>
